/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2015 Umeng, Inc
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.umeng.comm.ui.imagepicker.activities;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.qianxx.draw.R;
import com.qianxx.base.BaseAty;
import com.qianxx.base.IConstants;
import com.qianxx.base.Urls;
import com.qianxx.base.request.Config;
import com.qianxx.base.request.RM;
import com.qianxx.base.request.RequestBean;
import com.qianxx.base.uploadFile.FormFile;
import com.qianxx.base.uploadFile.HttpRequester;
import com.qianxx.base.utils.SPUtil;
import com.qianxx.base.utils.SelectImageUtils;
import com.qianxx.base.utils.StringUtil;
import com.qianxx.base.utils.TimeUtil;
import com.qianxx.base.utils.ToastUtil;
import com.qianxx.base.utils.ZoomBitmap;
import com.umeng.comm.core.beans.CommConfig;
import com.umeng.comm.core.beans.CommUser;
import com.umeng.comm.core.beans.Source;
import com.umeng.comm.core.constants.Constants;
import com.umeng.comm.core.impl.CommunitySDKImpl;
import com.umeng.comm.core.login.LoginListener;
import com.umeng.comm.core.utils.CommonUtils;
import com.umeng.comm.core.utils.ResFinder;
import com.umeng.comm.core.utils.ToastMsg;
import com.umeng.comm.ui.activities.BrithDatePickerActivity;
import com.umeng.comm.ui.fragments.UserInfoFragment;
import com.umeng.comm.ui.imagepicker.dialogs.ClipImageDialog;
import com.umeng.comm.ui.imagepicker.mvpview.MvpUserProfileSettingView;
import com.umeng.comm.ui.imagepicker.presenter.impl.UserSettingPresenter;
import com.umeng.comm.ui.imagepicker.widgets.RoundImageView;
import com.umeng.community.example.bean.MyBean;
import com.umeng.community.example.bean.MyInfo;
import com.umeng.community.example.bean.UserBean;

import java.io.File;
import java.util.HashMap;
import java.util.Map;


/**
 * 设置页面 注意：此Activity的名字不能修改，数据层需要回调此Activity
 */
//// TODO: 16/1/25 第一次登录逻辑跳转到话题界面有问题 
public class SettingActivity extends BaseAty implements MvpUserProfileSettingView {

    private ClipImageDialog mClipImageDialog;

    // 选择出生年月的requestCode
    private static final int BRITH = 1;

    private RoundImageView img;

    private EditText mName;

    private TextView mMan;

    private TextView mWoman;

    private EditText mBrith;

    private EditText mSchool;

    private EditText mInterest;

    private EditText mSpecialty;

    private String sex = "";
    //是否有图片
    private boolean isSave = false;
    //是否是编辑页面
    private boolean isEdit = true;
    // 头像路径名称
    private String pathName;
    // 文件上传
    private FormFile uploadFile;

    private MyInfo info;

    private UserSettingPresenter mPresenter;

    private boolean isRegisterUserNameInvalid = false;//注册时，昵称是否无效

    private boolean isFirst = false; //是否第一次登录

    private CommUser user;

    private ProgressDialog mProgressDialog;

    private CommUser.Gender mGender;

    private Bitmap mBitmap;

    private String openid;
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.perfect);
        isEdit = getIntent().getBooleanExtra("isEdit", false);
        mPresenter = new UserSettingPresenter(this, this);
        mProgressDialog = new ProgressDialog(this);
        judgeIsFirst();
        initView();
        if (isEdit){
            loadInfo();
        }else {
            setFirstData();
        }
    }

    private void setFirstData() {
        img.setImageUrl(user.iconUrl);
        mName.setText(user.name.trim());
        Log.i("SettingActivity",mName.getText().length()+"");
        if (user.gender == CommUser.Gender.MALE) {
            mMan.setSelected(true);
            mWoman.setSelected(false);
            sex = "1";
            mGender = CommUser.Gender.MALE;
        } else {
            mWoman.setSelected(true);
            mMan.setSelected(false);
            sex = "0";
            mGender = CommUser.Gender.FEMALE;
        }
//        String mStr = TimeUtil.getStrTime5(info.getBirthday());
//        mBrith.setText(mStr.substring(0, 7));
//        mSchool.setText(info.getSchoolGrade());
//        mInterest.setText(info.getInterest());
//        mSpecialty.setText(info.getSpecialty());
    }
    public void judgeIsFirst() {
        Bundle mExtra = getIntent().getExtras();
        if (mExtra != null && mExtra.containsKey(Constants.USER_SETTING)) {
            isFirst = true;
//            user = mExtra.getParcelable(Constants.USER);
//            openid =mExtra.getParcelable(Constants.ID);
            user = CommConfig.getConfig().loginedUser;
//            openid = mExtra.getParcelable(Constants.PROTOCOL_KEY_UID);
            Log.e("com.draw","source_uid = " + user);
            isRegisterUserNameInvalid = mExtra.getBoolean(Constants.REGISTER_USERNAME_INVALID);
            mPresenter.setFirstSetting(true);
            ThirdLogin(user);
            finish();
        } else {
            isFirst = false;
            user = CommonUtils.getLoginUser(this);
        }
    }


    /**
     * 检查检查昵称、年龄数据是否正确</br>
     *
     * @return
     */
    private boolean checkData() {
        String name = mName.getText().toString().trim();
        if (TextUtils.isEmpty(name) && isFirst && !isRegisterUserNameInvalid) {
            name = user.name;
        }
        if (TextUtils.isEmpty(name)) {
            ToastMsg.showShortMsgByResName("umeng_comm_user_center_no_name");
            return false;
        }
        return true;
    }

    public void registerOrUpdateUserInfo() {
        boolean flag = checkData();
        if (!flag) {
            return;
        }
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setMessage(ResFinder.getString("umeng_comm_update_user_info"));
        if (isRegisterUserNameInvalid) {
            register();
        } else {
            updateUserInfo();
        }
    }

    private void register() {
        user.name = mName.getText().toString().trim();
        user.gender = mGender;
        user.age = StringUtil.age(TimeUtil.getStrTime5(info.getBirthday()));
        mPresenter.register(user);
    }

    /**
     * 更新用户信息</br>
     */
    private void updateUserInfo() {

        final CommUser newUser = CommConfig.getConfig().loginedUser;
        if (TextUtils.isEmpty(mName.getText().toString())) {
            newUser.name = mName.getHint().toString();
        } else {
            newUser.name = mName.getText().toString();
        }
        newUser.gender = mGender;
        newUser.age = StringUtil.age(TimeUtil.getStrTime5(info.getBirthday()));
        mPresenter.updateUserProfile(newUser);
    }


    /**
     * 处理保存事件的逻辑。如果当前fragment是用户设置页面，则执行更新用户接口</br>
     */
    private void dealSaveLogic() {
        registerOrUpdateUserInfo();
        // showFragment(mSettingFragment);
    }


    @Override
    public void topLeftClick(View v) {
        if (!isEdit) {
            CommunitySDKImpl.getInstance().logout(this, new LoginListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onComplete(int stCode, CommUser userInfo) {
//                    ThirdLoginOutRequestUtils.getInstance(SettingActivity.this).ThirdLoginOut();
                    finish();
                }
            });
        }else {
            finish();
        }
    }

    @Override
    public void topRightClick(View v) {
        super.topRightClick(v);
        if (invalid()) {
            //TODO
            if (isSave) {
                // 更新用户头像
                mClipImageDialog.updateUserPortrait(mBitmap);
            }
            btnUpload();

        }
    }

    private void loadData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("nickName", mName.getText().toString());
        map.put("birthday", TimeUtil.getLongTime(mBrith.getText() + ".01") + "");
        map.put("sex", sex);
        map.put("schoolGrade", mSchool.getText().toString());
        map.put("interest", mInterest.getText().toString());
        map.put("specialty", mSpecialty.getText().toString());
        requestDataWithoutLoading(IConstants.INFO, Urls.USER_INFO, RM.POST, MyBean.class, map);
    }

    private void loadInfo() {
        HashMap<String, String> map = new HashMap<>();
        requestData(IConstants.MORE, Urls.USER_GET, RM.POST, MyBean.class, map);
    }

    private void btnUpload() {

        showLoading();
        HttpRequester.OnRequestListener listener = new HttpRequester.OnRequestListener() {

            @Override
            public void onProgressing(int size, int allSize) {// TODO 上传过程
                Log.e("AddDrugsActivity", "已上传:" + size + "/总量:" + allSize);
            }

            @Override
            public void onFinish(String response) {
                hideLoading();
                if (TextUtils.isEmpty(response)) {
                    // hideLoading();
                    return;
                }
                MyBean fromJson = JSON.parseObject(response,
                        MyBean.class);
                if (fromJson == null) {
//                    Log.e("编辑头像信息异常：返回的JSON不能转换为UserBean对象", "JSON:" + response);
                    // hideLoading();
                    return;
                }
                if (fromJson.getStatus().equals("1")) {
                    ToastUtil.getInstance().toast("保存成功");
                    uploadFile = null;
                    loadData();
                } else {
                    ToastUtil.getInstance().toast("保存失败");
                    uploadFile = null;
                }
            }
        };
        FormFile[] files = null;
        if (uploadFile != null) {
            files = new FormFile[]{uploadFile};
        }
        Map<String, String> params = new HashMap<String, String>();
        if (!isSave) {
            params.put("headImgUrl", CommConfig.getConfig().loginedUser.iconUrl);
        }
        uploadFiles(Urls.USER_IMG, params, files, listener);
    }


    private void initView() {
        if (isEdit) {
//            showTitle("修改资料");
            showTitle("完善资料");
        } else {
            showTitle("完善资料");
            hideTopLeftLayout();

        }
        showTopRight("保存");
        img = (RoundImageView) findViewById(R.id.user_icon);
        img.setOnClickListener(this);

        mName = (EditText) findViewById(R.id.name_et);
//        mName.setText(user.name);
        Selection.setSelection(mName.getText(), mName.length());
        mMan = (TextView) findViewById(R.id.man_tv);
        mMan.setOnClickListener(this);
        mWoman = (TextView) findViewById(R.id.woman_tv);
        mWoman.setOnClickListener(this);
//        if (user.gender.equals(CommUser.Gender.FEMALE)) {
//            mWoman.setSelected(true);
//            mMan.setSelected(false);
//            sex = "0";
//            mGender = CommUser.Gender.FEMALE;
//        } else {
//            mMan.setSelected(true);
//            mWoman.setSelected(false);
//            sex = "1";
//            mGender = CommUser.Gender.MALE;
//        }

//        if (!isEdit){
//            img.setImageUrl(user.iconUrl);
//            mName.setText(user.name);
//            if (user.gender.equals(CommUser.Gender.FEMALE)) {
//                mWoman.setSelected(true);
//                mMan.setSelected(false);
//                sex = "0";
//                mGender = CommUser.Gender.FEMALE;
//            } else {
//                mMan.setSelected(true);
//                mWoman.setSelected(false);
//                sex = "1";
//                mGender = CommUser.Gender.MALE;
//            }
//        }else {
//            if (info!= null){
//                img.setImageUrl(info.getHeadImg());
//                mName.setText(info.getNickName());
//                if (info.getSex().equals("1")) {
//                    mMan.setSelected(true);
//                    mWoman.setSelected(false);
//                    sex = "1";
//                    mGender = CommUser.Gender.MALE;
//                } else {
//                    mWoman.setSelected(true);
//                    mMan.setSelected(false);
//                    sex = "0";
//                    mGender = CommUser.Gender.FEMALE;
//                }
//            }
//        }


        mBrith = (EditText) findViewById(R.id.brithday_et);
        mBrith.setFocusable(false);
        mBrith.setOnClickListener(this);
        mSchool = (EditText) findViewById(R.id.school_et);
        mInterest = (EditText) findViewById(R.id.interest_et);
        mSpecialty = (EditText) findViewById(R.id.specialty_et);
        findViewById(R.id.name_lay).setOnClickListener(this);
        findViewById(R.id.brithday_lay).setOnClickListener(this);
        findViewById(R.id.school_lay).setOnClickListener(this);
        findViewById(R.id.interest_lay).setOnClickListener(this);
        findViewById(R.id.specialty_lay).setOnClickListener(this);
        valideEdit(mName);
        valideEdit(mSchool);
        valideEdit(mInterest);
        valideEdit(mSpecialty);
    }


    private void valideEdit(final EditText editText){

        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String str = editText.getText().toString();
                if (str.length() > 0) {
                    if (!invalidStr(str)) {
                        ToastUtil.getInstance().toast("只能输入汉字、数字、字母、下划线:");
                        String str2 = editText.getText().toString()
                                .substring(0, start);
                        editText.setText(str2);
                        Log.i("ss", str);
                    }

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };
        editText.addTextChangedListener(textWatcher);
    }

    private boolean invalidStr(String str){
        if (StringUtil.compile(str)){
            return  true;
        }
        return false;
    }
    private void setData() {
        img.setImageUrl(info.getHeadImg());
        mName.setText(info.getNickName());
        if (info.getSex().equals("1")) {
            mMan.setSelected(true);
            mWoman.setSelected(false);
            sex = "1";
            mGender = CommUser.Gender.MALE;
        } else {
            mWoman.setSelected(true);
            mMan.setSelected(false);
            sex = "0";
            mGender = CommUser.Gender.FEMALE;
        }
        String mStr = TimeUtil.getStrTime5(info.getBirthday());
        mBrith.setText(mStr.substring(0, 7));
        mSchool.setText(info.getSchoolGrade());
        mInterest.setText(info.getInterest());
        mSpecialty.setText(info.getSpecialty());
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            // 点击选择头像
            case R.id.user_icon:
//                if (isRegisterUserNameInvalid) {
//                    ToastMsg.showShortMsgByResName("umeng_comm_before_save");
//                } else {
                    selectProfile();
//                }
                break;
            case R.id.man_tv:
                mMan.setSelected(true);
                mWoman.setSelected(false);
                sex = "1";
                mGender = CommUser.Gender.MALE;
                break;
            case R.id.woman_tv:
                mMan.setSelected(false);
                mWoman.setSelected(true);
                sex = "0";
                mGender = CommUser.Gender.FEMALE;
                break;
            case R.id.brithday_et:
                BrithDatePickerActivity.actionStart(this, BRITH);
                break;
            default:
                break;
        }
    }

    private boolean invalid() {
        if (TextUtils.isEmpty(user.iconUrl) && !isSave) {
            ToastUtil.getInstance().toast("请选择头像");
            return false;
        }
        if (TextUtils.isEmpty(mName.getText().toString())) {
            ToastUtil.getInstance().toast("请输入昵称");
            return false;
        }
        if (mName.getText().length() > 6) {
            ToastUtil.getInstance().toast("昵称不能超过6个字符哦");
            return false;
        }
        if (StringUtil.isPunctuation(mName.getText().toString())){
            ToastUtil.getInstance().toast("不能输入非法字符哦");
            return false;
        }
        if (TextUtils.isEmpty(sex)) {
            ToastUtil.getInstance().toast("请选择性别");
            return false;
        }
        if (TextUtils.isEmpty(mBrith.getText().toString())) {
            ToastUtil.getInstance().toast("请选择出生年月");
            return false;
        }
        if (mSchool.getText().length() > 7){
            ToastUtil.getInstance().toast("学校不能超过7个字符哦");
            return false;
        }
        if (mInterest.getText().length() > 6){
            ToastUtil.getInstance().toast("兴趣不能超过6个字符哦");
            return false;
        }
        if (mSpecialty.getText().length() > 6){
            ToastUtil.getInstance().toast("特长不能超过6个字符哦");
            return false;
        }
        return true;
    }


    /**
     * 从相册中选择头像</br>
     */
    private void selectProfile() {
        Intent pickImageIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        pickImageIntent.setType("image/png;image/jpeg");
        startActivityForResult(pickImageIntent, Constants.PIC_SELECT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 防止在选择图片的时候按返回键
        if (data == null) {
            return;
        }
        // 从相册中选择图片
        if (requestCode == Constants.PIC_SELECT) {
            int style = ResFinder.getStyle("umeng_comm_dialog_fullscreen");
            // 显示剪切图片的Dialog
            mClipImageDialog = new ClipImageDialog(this, data.getData(), style);
            mClipImageDialog.setOnClickSaveListener(mOnSaveListener);
            mClipImageDialog.show();

        }
        if (requestCode == BRITH) {
            if (resultCode == BrithDatePickerActivity.Result_Select) {
                // 设置出生年月
                String str = "";
                int year = data.getIntExtra(BrithDatePickerActivity.YEAR, 2016);
                int month = data.getIntExtra(BrithDatePickerActivity.MONTH, 1);
                if (month < 10) {
                    str = "0" + month;
                }else {
                    str = month + "";
                }
//                int day = data.getIntExtra(DataPickerActivity.DAY, 1);
                mBrith.setText(year + "." + str);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 剪切图片dialog页面，点击保存时的回调，更新UI</br>
     */
    private ClipImageDialog.OnClickSaveListener mOnSaveListener = new ClipImageDialog.OnClickSaveListener() {

        @Override
        public void onClickSave(Bitmap bitmap) {

            try {
                img.setImageBitmap(bitmap);
                mBitmap = bitmap;
                isSave = true;

                pathName = ZoomBitmap.bitmap2FilePath2(mBitmap,
                        SelectImageUtils.getImageName());

            } catch (Exception e) {
                e.printStackTrace();
            }
            File file = new File(pathName);
            uploadFile = new FormFile(pathName, file, "headImg",
                    null, null);

        }
    };


    public static void actionStart(Context context, boolean isEdit) {
        Intent intent = new Intent(context, SettingActivity.class);
        intent.putExtra("isEdit", isEdit);
        context.startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            if (!isEdit) {
                CommunitySDKImpl.getInstance().logout(this, new LoginListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onComplete(int stCode, CommUser userInfo) {
//                    ThirdLoginOutRequestUtils.getInstance(SettingActivity.this).ThirdLoginOut();
                        finish();
                    }
                });
                return true;
            }
        }

        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void requestSuccess(RequestBean baseBean, Config config) {
        super.requestSuccess(baseBean, config);
        hideLoading();
        if (baseBean.getRequestTag().equals(IConstants.INFO)) {//修改后，保存数据
            MyBean bean = (MyBean) baseBean;
            info = bean.getData();
            dealSaveLogic();
            SPUtil.getInstance().setLongAge(TimeUtil.getStrTime5(info.getBirthday()));
            SPUtil.getInstance().setAge(StringUtil.age(TimeUtil.getStrTime5(info.getBirthday())) + "");
            UserInfoFragment.isRefresh = true;
//            ToastUtil.getInstance().toast(StringUtil.age(TimeUtil.getStrTime5(info.getBirthday())) + "");
            finish();
        } else if (baseBean.getRequestTag().equals(IConstants.MORE)) {//获取数据
            MyBean bean = (MyBean) baseBean;
            info = bean.getData();
            setData();
            SPUtil.getInstance().setLongAge(TimeUtil.getStrTime5(info.getBirthday()));
            SPUtil.getInstance().setAge(StringUtil.age(TimeUtil.getStrTime5(info.getBirthday())) + "");
//            ToastUtil.getInstance().toast(StringUtil.age(TimeUtil.getStrTime5(info.getBirthday())) + "");
        } else if (baseBean.getRequestTag().equals(IConstants.REQUEST)){//请求第三方登录接口
            UserBean userBean = (UserBean) baseBean;
            SPUtil.getInstance().setToken(userBean.getData().getToken());
            loadInfo();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 第三方登录后，登录服务器
     */
    public void ThirdLogin(CommUser userInfo) {
        HashMap<String, String> map = new HashMap<>();
        if (userInfo.source == Source.QQ) {
//            SPUtil.getInstance().setType("QQ");
            map.put("type", "qq");
        } else if (userInfo.source == Source.WEIXIN) {
//            SPUtil.getInstance().setType("wx");
            map.put("type", "wx");
        } else if (userInfo.source == Source.SINA) {
//            SPUtil.getInstance().setType("wb");
            map.put("type", "wb");
        }
        map.put("openId", userInfo.sourceUid);
        map.put("nickName", userInfo.name);
        map.put("headImgUrl", userInfo.iconUrl);
        requestDataWithoutLoading(IConstants.REQUEST, Urls.THIRDLOGIN_LIST, RM.POST, UserBean.class, map);
    }
}
